package com.theta.gateway.infra.common.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Redis工具类
 */
@Component
@SuppressWarnings("unchecked")
public class RedisUtils {

    /**
     * 默认过期时长为24小时，单位：秒
     */
    public final static long DEFAULT_EXPIRE = 60 * 60 * 24L;

    /***
     * 30分钟
     */
    public final static long HALF_HOUR_EXPIRE = 60 * 30;


    /**
     * 过期时长为1小时，单位：秒
     */
    public final static long HOUR_ONE_EXPIRE = 60 * 60 * 1L;

    /**
     * 过期时长为6小时，单位：秒
     */
    public final static long HOUR_SIX_EXPIRE = 60 * 60 * 6L;

    /**
     * 不设置过期时长
     */
    public final static long NOT_EXPIRE = -1L;

    @SuppressWarnings("rawtypes")
    @Autowired
    private RedisTemplate redisTemplate;

    public void set(String key, Object value, long expire) {
        redisTemplate.opsForValue().set(key, value);
        if (expire != NOT_EXPIRE) {
            expire(key, expire);
        }
    }

    public void set(String key, Object value) {
        set(key, value, DEFAULT_EXPIRE);
    }

    public Object get(String key, long expire) {
        Object value = redisTemplate.opsForValue().get(key);
        if (expire != NOT_EXPIRE) {
            expire(key, expire);
        }
        return value;
    }

    public Object get(String key) {
        return get(key, NOT_EXPIRE);
    }

    public void delete(String key) {
        redisTemplate.delete(key);
    }


    public void removePattern(String pattern) {
        Set<Serializable> keys = this.redisTemplate.keys(pattern);
        if (keys.size() > 0) {
            this.redisTemplate.delete(keys);
        }

    }

    public void delete(Collection<String> keys) {
        redisTemplate.delete(keys);
    }

    public Object hGet(String key, String field) {
        return redisTemplate.opsForHash().get(key, field);
    }

    public Map<String, Object> hGetAll(String key) {
        HashOperations<String, String, Object> hashOperations = redisTemplate.opsForHash();
        return hashOperations.entries(key);
    }

    public void hMSet(String key, Map<String, Object> map) {
        hMSet(key, map, DEFAULT_EXPIRE);
    }

    public void hMSet(String key, Map<String, Object> map, long expire) {
        redisTemplate.opsForHash().putAll(key, map);

        if (expire != NOT_EXPIRE) {
            expire(key, expire);
        }
    }

    public void hSet(String key, String field, Object value) {
        hSet(key, field, value, DEFAULT_EXPIRE);
    }

    public void hSet(String key, String field, Object value, long expire) {
        redisTemplate.opsForHash().put(key, field, value);

        if (expire != NOT_EXPIRE) {
            expire(key, expire);
        }
    }

    public void expire(String key, long expire) {
        redisTemplate.expire(key, expire, TimeUnit.SECONDS);
    }

    public void hDel(String key, Object... fields) {
        redisTemplate.opsForHash().delete(key, fields);
    }

    public void leftPush(String key, Object value) {
        leftPush(key, value, DEFAULT_EXPIRE);
    }

    public void leftPush(String key, Object value, long expire) {
        redisTemplate.opsForList().leftPush(key, value);

        if (expire != NOT_EXPIRE) {
            expire(key, expire);
        }
    }

    public Object rightPop(String key) {
        return redisTemplate.opsForList().rightPop(key);
    }


    /**
     * 判断缓存中是否有对应的value
     *
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 尝试获取分布式锁
     *
     * @param lockKey    锁
     * @param requestId  请求标识
     * @param expireTime 超期时间
     * @return 是否获取成功
     */
    public boolean tryGetDistributedLock(String lockKey, Object requestId, int expireTime) {

        Boolean flag = redisTemplate.opsForValue().setIfAbsent(lockKey, requestId);
        if (flag && expireTime > 0) {
            redisTemplate.expire(lockKey, expireTime, TimeUnit.SECONDS);
        }
        return flag;

    }

    /**
     * 释放redis锁
     *
     * @param lockKey
     */
    public void releaseLock(String lockKey, String requestId) {
        if (get(lockKey) != null && get(lockKey).toString().equals(requestId)) {

            redisTemplate.delete(lockKey);
        }

    }

    public int incr(String key, Long liveTime) {
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        int increment = (int) entityIdCounter.incrementAndGet();

        if (liveTime != null) {//初始设置过期时间
            entityIdCounter.expire(liveTime, TimeUnit.HOURS);
        }
        return increment;
    }

    public int decr(String key, Long liveTime) {
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        int decrement = (int) entityIdCounter.decrementAndGet();

        if (liveTime != null) {//初始设置过期时间
            entityIdCounter.expire(liveTime, TimeUnit.HOURS);
        }
        return decrement;
    }



    /**
     * 向set中 添加记录，
     * sadd 将一个或多个 member 元素加入到集合 key 当中，已经存在于集合的 value 元素将被忽略。
     * @param key
     * @param value
     * @return
     */
    public void sadd(String key,String... value) {
        redisTemplate.opsForSet().add(key,value);
        expire(key, DEFAULT_EXPIRE);
    }

    /**
     * 向set中 添加记录，
     * sadd 将一个或多个 member 元素加入到集合 key 当中，已经存在于集合的 value 元素将被忽略。
     * @param key
     * @param expire
     * @param value
     * @return
     */
    public void sadd(String key,int expire,String... value) {
        redisTemplate.opsForSet().add(key,value);
        if (expire != NOT_EXPIRE) {
            expire(key, expire);
        }
    }

    /**
     * 删除set中 指定的元素
     *
     * @param key
     * @param member
     * @return
     */
    public void srem(String key, String... member) {
        redisTemplate.opsForSet().remove(key,member);
    }


    /**
     * 判断set中元素是否存在
     *
     * @param key
     * @param value
     * @return
     */
    public boolean ifExist(String key, String value) {
        boolean result = redisTemplate.opsForSet().isMember(key, value);
        return result;
    }

    /**
     * 获取set 中的所有元素
     *
     * @param key
     * @return
     */
    public Set<String> smembers(String key) {
        Set<String> result = redisTemplate.opsForSet().members(key);
        return result;
    }


}